#!/usr/bin/env bash
# Summary: Show the current Node version
set -e
[ -n "$NODENV_DEBUG" ] && set -x

if [ -z "$NODENV_VERSION" ]; then
  NODENV_VERSION_FILE="$(nodenv-version-file)"
  NODENV_VERSION="$(nodenv-version-file-read "$NODENV_VERSION_FILE" || true)"
fi

OLDIFS="$IFS"
IFS=$'\n' scripts=(`nodenv-hooks version-name`)
IFS="$OLDIFS"
for script in "${scripts[@]}"; do
  source "$script"
done

if [ -z "$NODENV_VERSION" ] || [ "$NODENV_VERSION" = "system" ]; then
  echo "system"
  exit
fi

version_exists() {
  local version="$1"
  [ -d "${NODENV_ROOT}/versions/${version}" ]
}

if version_exists "$NODENV_VERSION"; then
  echo "$NODENV_VERSION"
elif version_exists "${NODENV_VERSION/v/}"; then
  echo "${NODENV_VERSION/v/}"
elif version_exists "${NODENV_VERSION#node-}"; then
  echo "${NODENV_VERSION#node-}"
elif version_exists "${NODENV_VERSION#node-v}"; then
  echo "${NODENV_VERSION#node-v}"
else
  echo "nodenv: version \`$NODENV_VERSION' is not installed (set by $(nodenv-version-origin))" >&2
  exit 1
fi
